"""
控制流程综合练习
学习目标：
1. 综合运用if、elif、else
2. 综合运用for、while循环
3. 综合运用break、continue
4. 解决实际问题
"""

print("=" * 60)
print(" " * 15 + "控制流程综合练习")
print("=" * 60)
print()

# ==================== 练习1：数字游戏 ====================
print("=" * 60)
print("练习1：猜数字游戏")
print("=" * 60)

import random

secret = random.randint(1, 100)
max_guesses = 7

print(f"我想了一个1-100之间的数字，你有{max_guesses}次机会猜")
print()

# 模拟猜测
guesses = [50, 75, 88, 94, 97, 99, 100]
guess_index = 0

for attempt in range(1, max_guesses + 1):
    if guess_index < len(guesses):
        guess = guesses[guess_index]
    else:
        guess = secret
    guess_index += 1
    
    print(f"第{attempt}次猜测：{guess}")
    
    if guess == secret:
        print(f"🎉 恭喜！猜对了！答案是{secret}")
        print(f"你用了{attempt}次")
        break
    elif guess < secret:
        print("  太小了！")
    else:
        print("  太大了！")
else:
    print(f"\n😢 次数用完了！答案是{secret}")

print()

# ==================== 练习2：成绩管理系统 ====================
print("=" * 60)
print("练习2：学生成绩管理系统")
print("=" * 60)

students = [
    {"name": "张三", "scores": [85, 90, 78]},
    {"name": "李四", "scores": [92, 88, 95]},
    {"name": "王五", "scores": [78, 85, 82]},
    {"name": "赵六", "scores": [55, 60, 58]},
]

print("学生成绩表：")
print("-" * 60)
print(f"{'姓名':<8} {'语文':>6} {'数学':>6} {'英语':>6} {'总分':>6} {'平均':>6} {'等级':>6}")
print("-" * 60)

for student in students:
    name = student["name"]
    scores = student["scores"]
    total = sum(scores)
    average = total / len(scores)
    
    # 等级评定
    if average >= 90:
        grade = "优秀"
    elif average >= 80:
        grade = "良好"
    elif average >= 70:
        grade = "中等"
    elif average >= 60:
        grade = "及格"
    else:
        grade = "不及格"
    
    print(f"{name:<8} {scores[0]:>6} {scores[1]:>6} {scores[2]:>6} {total:>6} {average:>6.1f} {grade:>6}")

print("-" * 60)

# 统计
excellent_count = sum(1 for s in students if sum(s["scores"])/len(s["scores"]) >= 90)
good_count = sum(1 for s in students if 80 <= sum(s["scores"])/len(s["scores"]) < 90)
medium_count = sum(1 for s in students if 70 <= sum(s["scores"])/len(s["scores"]) < 80)
pass_count = sum(1 for s in students if 60 <= sum(s["scores"])/len(s["scores"]) < 70)
fail_count = sum(1 for s in students if sum(s["scores"])/len(s["scores"]) < 60)

print(f"\n统计：优秀{excellent_count}人，良好{good_count}人，中等{medium_count}人，及格{pass_count}人，不及格{fail_count}人")

print()

# ==================== 练习3：购物车系统 ====================
print("=" * 60)
print("练习3：购物车结算系统")
print("=" * 60)

products = [
    {"name": "Python书籍", "price": 89, "quantity": 2},
    {"name": "鼠标", "price": 59, "quantity": 1},
    {"name": "键盘", "price": 199, "quantity": 1},
    {"name": "U盘", "price": 39, "quantity": 3},
]

print("购物清单：")
print("-" * 60)

total_amount = 0
for i, product in enumerate(products, 1):
    subtotal = product["price"] * product["quantity"]
    total_amount += subtotal
    print(f"{i}. {product['name']:<12} ¥{product['price']:>6} × {product['quantity']:>2} = ¥{subtotal:>7.2f}")

print("-" * 60)
print(f"{'商品总价：':<20} ¥{total_amount:>7.2f}")

# 会员折扣
is_vip = True
if is_vip:
    if total_amount >= 500:
        discount_rate = 0.8
        discount_desc = "VIP + 满500"
    elif total_amount >= 300:
        discount_rate = 0.85
        discount_desc = "VIP + 满300"
    else:
        discount_rate = 0.9
        discount_desc = "VIP会员"
else:
    if total_amount >= 500:
        discount_rate = 0.9
        discount_desc = "满500"
    else:
        discount_rate = 1.0
        discount_desc = "无折扣"

if discount_rate < 1.0:
    discounted_amount = total_amount * discount_rate
    saved = total_amount - discounted_amount
    print(f"{'折扣('+ discount_desc +')：':<20} -{saved:>6.2f} ({int(discount_rate*10)}折)")
    total_amount = discounted_amount

# 运费
if total_amount >= 199:
    shipping = 0
    print(f"{'运费（满199免运费）：':<20} ¥{shipping:>7.2f}")
else:
    shipping = 10
    print(f"{'运费：':<20} ¥{shipping:>7.2f}")
    total_amount += shipping

print("-" * 60)
print(f"{'应付金额：':<20} ¥{total_amount:>7.2f}")

print()

# ==================== 练习4：ATM取款机 ====================
print("=" * 60)
print("练习4：ATM取款系统（模拟）")
print("=" * 60)

balance = 5000  # 余额
pin = "123456"  # 密码

# 模拟操作序列
actions = [("1", "123456"), ("2", "500"), ("4", "")]
action_index = 0

while action_index < len(actions):
    print("\n===== ATM系统 =====")
    print("1. 查询余额")
    print("2. 取款")
    print("3. 存款")
    print("4. 退出")
    print("==================")
    
    choice, param = actions[action_index]
    action_index += 1
    
    print(f"选择：{choice}")
    
    if choice == "1":
        # 查询余额
        password = param
        print(f"输入密码：{'*' * len(password)}")
        if password == pin:
            print(f"✅ 当前余额：¥{balance}")
        else:
            print("❌ 密码错误")
    
    elif choice == "2":
        # 取款
        amount = int(param)
        print(f"取款金额：¥{amount}")
        
        if amount <= 0:
            print("❌ 金额必须大于0")
        elif amount > balance:
            print(f"❌ 余额不足（当前余额：¥{balance}）")
        elif amount % 100 != 0:
            print("❌ 金额必须是100的倍数")
        else:
            balance -= amount
            print(f"✅ 取款成功！剩余余额：¥{balance}")
    
    elif choice == "3":
        # 存款
        amount = int(param) if param else 0
        print(f"存款金额：¥{amount}")
        
        if amount <= 0:
            print("❌ 金额必须大于0")
        else:
            balance += amount
            print(f"✅ 存款成功！当前余额：¥{balance}")
    
    elif choice == "4":
        print("👋 感谢使用，再见！")
        break
    
    else:
        print("❌ 无效选择")

print()

# ==================== 练习5：打印图案 ====================
print("=" * 60)
print("练习5：打印各种图案")
print("=" * 60)

# 1. 数字三角形
print("数字三角形：")
for i in range(1, 6):
    for j in range(1, i + 1):
        print(j, end=" ")
    print()

print()

# 2. 倒三角
print("倒三角：")
for i in range(5, 0, -1):
    for j in range(i):
        print("*", end=" ")
    print()

print()

# 3. 菱形
print("菱形：")
n = 5
for i in range(n):
    print(" " * (n - i - 1) + "*" * (2 * i + 1))
for i in range(n - 2, -1, -1):
    print(" " * (n - i - 1) + "*" * (2 * i + 1))

print()

# ==================== 练习6：质数生成器 ====================
print("=" * 60)
print("练习6：生成质数")
print("=" * 60)

def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True

print("100以内的所有质数：")
primes = []
for num in range(2, 101):
    if is_prime(num):
        primes.append(num)

# 每行打印10个
for i in range(0, len(primes), 10):
    line_primes = primes[i:i+10]
    print("  " + " ".join(f"{p:3d}" for p in line_primes))

print(f"\n共{len(primes)}个质数")

print()

# ==================== 练习7：斐波那契数列 ====================
print("=" * 60)
print("练习7：斐波那契数列")
print("=" * 60)

n = 15
print(f"生成前{n}项斐波那契数列：")

fib = [0, 1]
for i in range(2, n):
    fib.append(fib[-1] + fib[-2])

print(fib)

# 找出小于1000的所有项
print("\n小于1000的斐波那契数：")
a, b = 0, 1
fib_list = []
while a < 1000:
    fib_list.append(a)
    a, b = b, a + b

print(fib_list)

print()

# ==================== 练习8：文本分析 ====================
print("=" * 60)
print("练习8：文本字符统计")
print("=" * 60)

text = "Hello Python! Python is awesome. I love Python 3.11!"
print(f"文本：{text}")
print()

# 统计各类字符
letters = 0
digits = 0
spaces = 0
others = 0

for char in text:
    if char.isalpha():
        letters += 1
    elif char.isdigit():
        digits += 1
    elif char.isspace():
        spaces += 1
    else:
        others += 1

print("字符统计：")
print(f"  字母：{letters}个")
print(f"  数字：{digits}个")
print(f"  空格：{spaces}个")
print(f"  其他：{others}个")
print(f"  总计：{len(text)}个")

# 统计单词
words = text.split()
print(f"\n单词数：{len(words)}个")

# 统计Python出现次数
count = text.count("Python")
print(f"'Python'出现次数：{count}次")

print()

# ==================== 练习9：密码强度检测 ====================
print("=" * 60)
print("练习9：密码强度检测")
print("=" * 60)

def check_password_strength(password):
    """检测密码强度"""
    score = 0
    feedback = []
    
    # 长度检查
    length = len(password)
    if length >= 12:
        score += 2
        feedback.append("✅ 长度足够")
    elif length >= 8:
        score += 1
        feedback.append("⚠️ 长度一般")
    else:
        feedback.append("❌ 长度太短")
    
    # 包含小写字母
    if any(c.islower() for c in password):
        score += 1
        feedback.append("✅ 包含小写字母")
    else:
        feedback.append("❌ 缺少小写字母")
    
    # 包含大写字母
    if any(c.isupper() for c in password):
        score += 1
        feedback.append("✅ 包含大写字母")
    else:
        feedback.append("❌ 缺少大写字母")
    
    # 包含数字
    if any(c.isdigit() for c in password):
        score += 1
        feedback.append("✅ 包含数字")
    else:
        feedback.append("❌ 缺少数字")
    
    # 包含特殊字符
    if any(not c.isalnum() for c in password):
        score += 1
        feedback.append("✅ 包含特殊字符")
    else:
        feedback.append("❌ 缺少特殊字符")
    
    # 判断强度
    if score >= 5:
        strength = "强"
        color = "🟢"
    elif score >= 3:
        strength = "中等"
        color = "🟡"
    else:
        strength = "弱"
        color = "🔴"
    
    return score, strength, color, feedback

passwords = ["123456", "Abcd1234", "MyP@ssw0rd!", "python"]

for pwd in passwords:
    score, strength, color, feedback = check_password_strength(pwd)
    print(f"\n密码：{'*' * len(pwd)}")
    print(f"强度：{color} {strength} (得分：{score}/6)")
    print("详情：")
    for item in feedback:
        print(f"  {item}")

print()

# ==================== 练习10：成绩排名 ====================
print("=" * 60)
print("练习10：学生成绩排名")
print("=" * 60)

students = [
    {"name": "张三", "score": 85},
    {"name": "李四", "score": 92},
    {"name": "王五", "score": 78},
    {"name": "赵六", "score": 96},
    {"name": "钱七", "score": 88},
]

print("原始成绩：")
for s in students:
    print(f"  {s['name']}：{s['score']}分")

# 排序（冒泡排序演示）
n = len(students)
for i in range(n - 1):
    for j in range(n - 1 - i):
        if students[j]["score"] < students[j + 1]["score"]:
            students[j], students[j + 1] = students[j + 1], students[j]

print("\n排名：")
print("-" * 40)
for i, s in enumerate(students, 1):
    medal = "🥇" if i == 1 else "🥈" if i == 2 else "🥉" if i == 3 else "  "
    print(f"{medal} 第{i}名：{s['name']:<6} {s['score']}分")

print()

# ==================== 总结 ====================
print("=" * 60)
print(" " * 20 + "练习完成！")
print("=" * 60)
print("""
通过以上练习，你已经掌握了：

✅ 条件判断：if、elif、else
✅ 循环控制：for、while
✅ 循环控制：break、continue
✅ 循环嵌套：处理复杂问题
✅ 循环else：优雅的查找判断

这些知识可以解决：
- 游戏逻辑（猜数字）
- 数据处理（成绩统计、排名）
- 业务系统（购物车、ATM）
- 图案打印（各种形状）
- 算法实现（质数、斐波那契）
- 文本处理（字符统计）
- 数据验证（密码强度）

继续练习，编程能力会越来越强！🎉
""")
print("=" * 60)

